#!/usr/bin/python3
#******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/
"""
This is openEuler source counter script
"""

import sys
import os
import argparse
import re
import codecs
import IssueCounter

def get_merged_branches(issue_list, owner, outfile):
    """
    Get merged branches of issues listed
    """
    issue_counter = IssueCounter.IssueCounter()

    fp = codecs.open(outfile, mode='w', encoding="utf_8_sig")
    if not fp:
        return False
    header = "{},{},{},{}".format("issue_id", "owner", "repo", "merged_branches")
    print(header)
    fp.write("{}\n".format(header))

    for issue in issue_list:
        print("issue={}".format(issue))
        issue_id    = issue[0]
        owner       = issue[1]
        repo        = issue[2]

        print("scanning {}, repo={}".format(issue_id, repo))
        merged_branches = issue_counter.get_merged_branches(issue_id, repo, owner)
        merged_branches.sort()
        print(" |".join(merged_branches) + "\n")
        issue.append(" |".join(merged_branches))

        fp.write("{}\n".format(issue))
        fp.flush()
    fp.close()
    return True


def get_list(list_file_path):
    """
    Get list of input issue_list
    """
    lst = []
    if os.path.isfile(list_file_path):
        with open(list_file_path, 'r') as f:
            for ln in f:
                ln_temp = re.split('[ \t/]+', ln.strip())
                if len(ln_temp) < 2:
                    continue
                lst.append(ln_temp)
    else:
        lst = list(list_file_path.strip().split(" "))
    return lst


def save_to_csv_file(outfile, save_data):
    """
    save result to csv-1
    """
    fp = codecs.open(outfile, mode='w', encoding="utf_8_sig")
    if not fp:
        return False
    header = "{},{},{}".format("issue_id", "owner", "merged_branches")
    print(header)
    fp.write("{}\n".format(header))

    for line in save_data:
        print(line)
        fp.write("{}\n".format(line))
        fp.flush()
    fp.close()
    return True


def main():
    """
    Main entrance of the functionality
    """
    params = argparse.ArgumentParser()
    params.add_argument("-c", "--command", type=str,
                        choices=['mr_br', 'NA'], required=True,
                        help="The subcommand, as follows: mr_br, contribute")
    params.add_argument("-i", "--issuelist", type=str, required=True,
                        help="The issue list")
    params.add_argument("-p", "--project", type=str, default="src-openeuler",
                        help="The project name, default is src-openeuler")
    params.add_argument("-o", "--outfile", type=str, default="",
                        help="The output file, default is {command}_stat_result.csv")

    args = params.parse_args()

    if not args.command:
        print("args invalid, please use -h for help")
        quit()

    issue_list = get_list(args.issuelist)
    if not issue_list:
        print("issue list invalid")
        quit()

    if not args.outfile:
        outfile = "{}_stat_result.csv".format(args.command)
    else:
        outfile = args.outfile

    if args.command == "mr_br":
        if get_merged_branches(issue_list, args.project, outfile):
            print("Process get_merged_branches succeed!")
        else:
            print("Process get_merged_branches failed!")

if __name__ == "__main__":
    main()